<template>
  <el-container>
    <vHeadSpace />
    <el-container>
      <vAsideSpace />
      <el-container>
        <el-main class="main">
          <div class="content">
            <div class="md-layout">
              <!--第一部分：设备数量-->
              <div class="md-layout-item md-medium-size-50 md-xsmall-size-100 md-size-34">
                <stats-card data-background-color="green">
                  <template slot="header">
                    <!--    取消单击事件  @click="goOverview('可用')"      -->
                    <div class="info-pane">
                      <md-icon>可用</md-icon>
                    </div>
                  </template>
                  <template slot="content">
                    <h3 class="title">
                      {{baseInfo_zy.available}}
                      <small>台</small>
                    </h3>
                  </template>

                  <template slot="footer">
                    <div class="stats">可使用设备数量</div>
                  </template>
                </stats-card>
              </div>
              <div class="md-layout-item md-medium-size-50 md-xsmall-size-100 md-size-34">
                <stats-card data-background-color="#0919f0">
                  <template slot="header">
                    <div class="info-pane">
                      <md-icon>不可用</md-icon>
                    </div>
                  </template>

                  <template slot="content">
                    <h3 class="title">
                      {{baseInfo_zy.unaviNumber}}
                      <small>台</small>
                    </h3>
                  </template>

                  <template slot="footer">
                    <div class="stats">不可用设备数量</div>
                  </template>
                </stats-card>
              </div>
              <div class="md-layout-item md-medium-size-50 md-xsmall-size-100 md-size-34">
                <stats-card data-background-color="blue">
                  <template slot="header">
                    <div class="info-pane">
                      <md-icon>总计</md-icon>
                    </div>
                  </template>
                  <template slot="content">
                    <h3 class="title">
                      {{baseInfo_zy.total}}
                      <small>台</small>
                    </h3>
                  </template>

                  <template slot="footer">
                    <div class="stats">所有设备数量</div>
                  </template>
                </stats-card>
              </div>

              <!--   告警分布及内存、CPU利用率分布   -->
            </div>
            <div>
              <stats-card
                data-background-color="blue"
                style="margin-bottom: 5px;font-weight: bold; font-size: x-large"
                v-b-hover
              >
                <template slot="header" style="width: 100px">
                  <el-button
                    type="text"
                    style="
                      font-weight: bold; font-size: x-large;color: white"
                  >告警分布</el-button>
                </template>
              </stats-card>
            </div>
            <div>
              <el-card class="box-card">
                <!--                <div slot="header" class="clearfix">-->
                <!--                  <span>告警分布</span>-->
                <!--                </div>-->
                <div id="Alert_chart" style="width: 50%;height: 400px; margin:0px auto"></div>
                <!--        <div id="CPU_Memory_chart" style="width: 50%;height: 400px; float: right"></div>-->
              </el-card>
            </div>

            <!-- 高负载设备、最近告警项-->

            <div style="width: 200%;">
              <el-row>
                <el-col :span="12">
                  <stats-card
                    data-background-color="blue"
                    style="margin-bottom: 5px;font-weight: bold; font-size: x-large"
                    v-b-hover
                  >
                    <template slot="header" style="width: 100px">
                      <!--                      <el-tooltip placement="top">-->
                      <!--                        <div slot="content">配置注意事项:<br/>-->
                      <!--                          在windows和linux的agent上配置cpu利用率监控项时，键值必须为system.cpu.util<br/>-->
                      <!--                          在windows的agent上配置内存利用率监控项时，键值必须为vm.memory.util;在linux的agent上配置内存利用率监控项时，键值必须为vm.memory.utilization-->
                      <!--                        </div>-->
                      <el-button
                        type="text"
                        style="
                        font-weight: bold; font-size: x-large;color: white"
                      >高负载设备</el-button>
                      <!--                      </el-tooltip>-->
                    </template>
                  </stats-card>
                  <el-row style="width: 49%;float: left">
                    <el-card class="box-card">
                      <div slot="header" class="clearfix">
                        <span>设备监控Top5平均CPU利用率统计</span>
                        <el-button
                          style="float: right; padding: 3px 0"
                          type="text"
                          @click="high_cpu_loadvue"
                        >详情</el-button>
                      </div>
                      <el-table :data="highLoadsortedbycpu" stripe width="100%">
                        <el-table-column prop="number" label="序号" width="100">
                          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
                        </el-table-column>
                        <el-table-column prop="hostname" label="设备名" width="180"></el-table-column>
                        <el-table-column prop="CPUUtilization" label="CPU利用率" width="270">
                          <template slot-scope="scope">
                            <el-progress
                              :percentage="valueChange(scope.row.CPUUtilization)"
                              :color="customColorMethod"
                              :format="Textformat(scope.row.CPUUtilization)"
                              :stroke-width="3"
                            ></el-progress>
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-card>
                  </el-row>
                  <el-row style="width: 49%;float: right">
                    <el-card class="box-card">
                      <div slot="header" class="clearfix">
                        <span>设备监控Top5平均内存利用率统计</span>
                        <el-button
                          style="float: right; padding: 3px 0"
                          type="text"
                          @click="high_memory_loadvue"
                        >详情</el-button>
                      </div>
                      <el-table :data="highLoadsortedbymemory" width="50%">
                        <el-table-column prop="number" label="序号" width="100">
                          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
                        </el-table-column>
                        <el-table-column prop="hostname" label="设备名" width="180"></el-table-column>
                        <el-table-column prop="MemoryUtilization" label="内存利用率" width="280">
                          <template slot-scope="scope">
                            <el-progress
                              :percentage="valueChange(scope.row.MemoryUtilization)"
                              :color="customColorMethod"
                              :format="Textformat(scope.row.MemoryUtilization)"
                              :stroke-width="3"
                            ></el-progress>
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-card>
                  </el-row>
                </el-col>
                <el-col :span="12">
                  <div class="grid-content bg-purple-light"></div>
                </el-col>
              </el-row>
            </div>

            <div>
              <stats-card
                data-background-color="blue"
                style="margin-bottom: 5px;font-weight: bold; font-size: x-large"
                v-b-hover
              >
                <template slot="header" style="width: 100px">
                  <el-button
                    type="text"
                    style="
                      font-weight: bold; font-size: x-large;color: white"
                  >最近告警</el-button>
                </template>
              </stats-card>
            </div>

            <div style="margin-top: 10px">
              <el-card class="box-card">
                <!--                <div slot="header" class="clearfix">-->
                <!--                  <span>最近告警</span>-->
                <!--                </div>-->
                <el-table
                  :data="unhandledAlert"
                  style="width: 100%;cursor: pointer"
                  @row-click="ToUnhandledAlert"
                >
                  <el-table-column prop="id" min-width="12%" label="序号"></el-table-column>
                  <el-table-column prop="host" min-width="18%" label="主机名称"></el-table-column>

                  <el-table-column prop="name" min-width="54%" label="内容"></el-table-column>
                  <el-table-column prop="clock" min-width="16%" width="180" label="创建时间"></el-table-column>
                </el-table>
              </el-card>
            </div>
            <!--    拓扑图-->
            <!--    <div style="width: 100%">-->
            <!--      <el-row >-->
            <!--        <stats-card data-background-color="green" style="margin-bottom: 5px;font-weight: bold; font-size: x-large" v-b-hover="">-->
            <!--          <template slot="header" style="width: 100px">-->
            <!--            <el-tooltip placement="top">-->
            <!--              <div slot="content">配置注意事项:<br/>-->
            <!--                初始状态首页没有可展示拓扑图时需要在拓扑图页面选择指定拓扑图为首页展示。<br/>-->
            <!--                同时也可以在拓扑图页面修改首页展示的拓扑图。-->
            <!--              </div>-->
            <!--              <el-button type="text" style="font-weight: bold; font-size: x-large;color: white">拓扑图</el-button>-->
            <!--            </el-tooltip>-->
            <!--          </template>-->
            <!--        </stats-card>-->
            <!--      </el-row>-->
            <!--      <el-row>-->
            <!--        <el-card>-->
            <!--          <div slot="header" class="clearfix" >-->
            <!--            <span >当前拓扑图: {{mapName}}</span>-->
            <!--            <el-button style="float: right; padding: 3px 0" type="text"  @click="toMapList">详情</el-button>-->
            <!--          </div>-->
            <!--          &lt;!&ndash;    拓扑图画布&ndash;&gt;-->
            <!--          <canvas :width="computedSize(1)" :height="computedSize(2)" class="mapCanvas-content" id="mapListCanvas"></canvas>-->
            <!--        </el-card>-->
            <!--      </el-row>-->
            <!--    </div>-->
          </div>
        </el-main>
        <vFootSpace />
      </el-container>
    </el-container>
  </el-container>
</template>

<script>
import {
  StatsCard,
  ChartCard,
  NavTabsCard,
  NavTabsTable,
  OrderedTable
} from "@/components";
import axios from "axios";
import hostImgUrl from "../../public/img/topo/host.png";
import switchImgUrl from "../../public/img/topo/switch.png";
import serverImgUrl from "../../public/img/topo/host.png";
import notebookImgUrl from "../../public/img/topo/host.png";
import pictureImgUrl from "../../public/img/topo/picture.png";


export default {
  name: "Dashboard",
  components: {
    StatsCard,
  },
  async created() {},
  data() {
    return {
      baseInfo_fw: {},
      baseInfo_fw_two: [],
      baseInfo_zy: [],
      unhandledAlert: [],
      highLoadsortedbycpu: [],
      activeNames: ["1"],
      highLoadsortedbymemory: [],
      percentage: 40,
      customColor: "#409eff",
      customColors: [
        { color: "#f56c6c", percentage: 20 },
        { color: "#e6a23c", percentage: 40 },
        { color: "#5cb87a", percentage: 60 },
        { color: "#1989fa", percentage: 80 },
        { color: "#6f7ad3", percentage: 100 }
      ],
      //拓扑图对象
      map: {},
      mapName: "未选择",
      //图标路径
      hostImgUrl: hostImgUrl,
      switchImgUrl: switchImgUrl,
      serverImgUrl: serverImgUrl,
      notebookImgUrl: notebookImgUrl,
      pictureImgUrl: pictureImgUrl
    };
  },

  async mounted() {
    this.baseInfo_zy = await this.getBaseInfo();
    // this.baseInfo_fw = await this.getBaseInfo_alert();
    await this.getBaseInfo_alert();

    this.baseInfo_zy.unaviNumber =
      this.baseInfo_zy.unknownNumber + this.baseInfo_zy.unaviNumber;
    this.getHighLoadsortedbycpu();
    this.getHighLoadsortedbymemory();
    //未处理告警数据，暂时注释
    // this.drawAlertChart();
    this.unhandledAlert = await this.getUnhandledAlert();

    //加载拓扑图
    // let name = localStorage.getItem('homePageMap')
    // if(name !== null){
    //   this.mapName = name
    //   let _this = this
    //   //发送请求根据名字查询指定拓扑图
    //   axios.get('/map/getMapByName.action?name='+this.mapName).then(function (res){
    //     _this.map = res.data.content.result[0]
    //     _this.paintElements()
    //   })
    // }
  },
  watch: {
    //历史告警数据
    baseInfo_fw_two(val, old) {
      this.drawAlertChart(val);
    }
  },
  methods: {
    /*
     *  跳转总览页面
     * */
    goOverview(param) {
      this.$router.push({ path: "/monitorOverview", query: { text: param } });
    },
    /*跳转到高负载页面*/
    high_cpu_loadvue() {
      this.$router.push({
        path: "/highLoadHostList",
        query: { type: "CPUUtilization" }
      });
    },
    high_memory_loadvue() {
      this.$router.push({
        path: "/highLoadHostList",
        query: { type: "MemoryUtilization" }
      });
    },
    valueChange(value) {
      let relvalue = Math.round(value);
      return relvalue;
    },
    // 进度条进度显示
    Textformat(value) {
      return () => {
        return `${value}%`;
      };
    },

    ToUnhandledAlert(row, event, column) {
      console.log(row);
      this.$router.push({
        name: "UnhandledAlert",
        params: {
          host: row.host,
          hostid: row.hostid
        }
      });
    },
    /*
        控制进度条颜色
       */
    customColorMethod(percentage) {
      if (percentage < 30) {
        return "#5cb87a";
      } else if (percentage < 70) {
        return "#e6a23c";
      } else {
        return "#f56c6c";
      }
    },
    drawAlertChart(val) {
      let myChart = this.$echarts.init(document.getElementById("Alert_chart"));
      let option = {
        title: {
          text: "告警分布",
          left: "center"
        },
        tooltip: {
          trigger: "item"
        },
        legend: {
          orient: "vertical",
          left: "left"
        },
        series: [
          {
            name: "告警分布",
            type: "pie",
            radius: "50%",
            //未处理告警数据
            // data: [
            //   {value: this.baseInfo_fw.Disaster>0?this.baseInfo_fw.Disater:null, name: '灾难'},
            //   {value: this.baseInfo_fw.High>0?this.baseInfo_fw.High:null, name: '严重'},
            //   {value: this.baseInfo_fw.Average>0?this.baseInfo_fw.Average:null, name: '一般严重'},
            //   {value: this.baseInfo_fw.Warning>0?this.baseInfo_fw.Warning:null, name: '警告'},
            //   {value: this.baseInfo_fw.Information>0?this.baseInfo_fw.Information:null, name: '信息问题'},
            //   {value: this.baseInfo_fw.NotClassified>0?this.baseInfo_fw.NotClassified:null, name: '未分类'},
            // ],
            //历史告警数据
            data: [
              { value: val[0] > 0 ? val[0] : null, name: "未分类" },
              { value: val[1] > 0 ? val[1] : null, name: "信息类" },
              { value: val[2] > 0 ? val[2] : null, name: "警告" },
              { value: val[3] > 0 ? val[3] : null, name: "一般严重" },
              { value: val[4] > 0 ? val[4] : null, name: "严重" },
              { value: val[5] > 0 ? val[5] : null, name: "灾难" }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            }
          }
        ]
      };
      myChart.setOption(option);
      myChart.on("click", function(params) {
        var name = params.data.name;
        //跳转未处理
        // window.location.href = '/unhandledalert?name='+name;
        //跳转历史
        window.location.href = "/historicalAlarm?name=" + name;
      });
    },
    // drawCPUAndMemory(result){
    //   console.log(result);
    //   let maxOccupy = result[0];
    //   // 遍历找出流量图中的最大数据，进行动态设置流量图上限
    //   for (let i = 0; i < result.length; i++) {
    //     if (result[i] > maxOccupy){
    //       maxOccupy = result[i];
    //     }
    //   }
    //   let myOption = this.$echarts.init(document.getElementById("CPU_Memory_chart"));
    //   let option = {
    //     title: {
    //       text: '观察一种请关闭另一种 ---->'
    //     },
    //     tooltip: {
    //       trigger: 'axis'
    //     },
    //     legend: {
    //       data: ['内存', 'CPU']
    //     },
    //     grid: {
    //       left: '3%',
    //       right: '4%',
    //       bottom: '3%',
    //       containLabel: true
    //     },
    //     toolbox: {
    //       feature: {
    //         saveAsImage: {}
    //       }
    //     },
    //     xAxis: {
    //       type: 'category',
    //       boundaryGap: false,
    //       data: ['0-10', '10-20', '20-30', '30-40', '40-50', '50-60', '60-70', '70-80', '80-90', '90-100']
    //     },
    //     yAxis: {
    //       type: 'value',
    //     },
    //     series: [
    //       {
    //         name: 'CPU',
    //         type: 'line',
    //         stack: '总量',
    //         data: result.CPU
    //       },
    //       {
    //         name: '内存',
    //         type: 'line',
    //         stack: '总量',
    //         data: result.Memory
    //       },
    //     ]
    //   };
    //   myOption.setOption(option);
    // },
    getBaseInfo_alert() {
      //请求未处理，暂时更改为请求历史
      // let promise = axios.get('/dashboard/getNumberOfProblemInDifferentType.action');
      // return new Promise( (resolve, reject) => {
      //   promise.then( (response) =>{
      //     resolve(response.data.content);
      //   })
      // });

      //暂时请求跳转历史告警数据
      let _this = this;
      axios({
        methods: "get",
        url: "/problem/get_history_problem_count.action",
      
        params: {
          host_ids: "",
          check_list: "",
          time_of_severity:
            new Date().getTime() -
            3600 * 1000 * 24 * 365 * 10 +
            "," +
            new Date().getTime()
        }
      })
        .then(res => {
          // console.log("res!!!"+res);
          for (let i = 0; i < res.data.content.result.length; i++) {
            _this.baseInfo_fw_two.push(res.data.content.result[i]);
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },

    getBaseInfo() {
      let promise;

      promise = axios.get(
        "/dashboard/get_numbers_of_host_in_different_type.action"
      );

      return new Promise((resolve, reject) => {
        promise.then(response => {
          resolve(response.data.content.result);
        });
      });
    },
    getUnhandledAlert() {
      let promise;
      promise = axios({
        methods: "get",
        url: "/problem/get_current_unhandled_problem.action",
        params: {
          hostids: "", // hostId
          check_list: "未分类,严重,信息类,灾难,一般严重,警告", // severity
          current_page: "1",
          page_size: "10"
        }
      });
      return new Promise((resolve, reject) => {
        promise.then(res => {
          for (let i in res.data.content.result) {
            res.data.content.result[i]["id"] = parseInt(i) + 1;
          }
          resolve(res.data.content.result.slice(0, 6));
        });
      });
    },
    getHighLoadsortedbycpu() {
      axios
        .post("/monitor/get_high_load_host_list.action", {
          name: "CPUUtilization",
          type: "dashboard"
        })
        .then(res => {
          for (let i in res.data.content.result) {
            res.data.content.result[i]["id"] = parseInt(i) + 1;
            res.data.content.result[i]["CPU_utilization"] = parseInt(
              res.data.content.result[i]["CPU_utilization"]
            );
            res.data.content.result[i]["Memory_utilization"] = parseInt(
              res.data.content.result[i]["Memory_utilization"]
            );
          }
          this.highLoadsortedbycpu = res.data.content.result;
        });
    },
    getHighLoadsortedbymemory() {
      axios
        .post("/monitor/get_high_load_host_list.action", {
          name: "MemoryUtilization",
          type: "dashboard"
        })
        .then(res => {
          for (let i in res.data.content.result) {
            res.data.content.result[i]["id"] = parseInt(i) + 1;
            res.data.content.result[i]["CPU_utilization"] = parseInt(
              res.data.content.result[i]["CPU_utilization"]
            );
            res.data.content.result[i]["Memory_utilization"] = parseInt(
              res.data.content.result[i]["Memory_utilization"]
            );
          }
          this.highLoadsortedbymemory = res.data.content.result;
        });
    },
    handleChange(val) {
      console.log(val);
    }
    //加载拓扑图场景，并绘制拓扑图
    //绘制拓扑图上的元素
    // paintElements: function (){
    //   let canvas = document.getElementById('mapListCanvas')
    //   let stage = new JTopo.Stage(canvas)
    //   let scene = new JTopo.Scene(stage)
    //   scene.clear()
    //   //图片映射
    //   let img = {"151":this.hostImgUrl, "156":this.switchImgUrl, "5":this.pictureImgUrl}
    //   let nodes = {}
    //   //绘制节点
    //   for(let i=0; i<this.map.selements.length; i++){
    //     let element = this.map.selements[i]
    //     let node = new JTopo.Node()
    //     node.fontColor = '0,0,0'
    //     node.text = element.label
    //     node.type = 3
    //     node.setImage(img[element.iconid_off], true)
    //     node.setLocation(parseInt(element.x), parseInt(element.y))
    //     node.dragable = false
    //     scene.add(node)
    //     nodes[element.selementid] = node
    //   }
    //   //绘制线
    //   for (let i = 0; i < this.map.links.length; i++) {
    //     let link = this.map.links[i]
    //     let l = new JTopo.Link(nodes[link.selementid1], nodes[link.selementid2])
    //     l.strokeColor = '10,204,80'
    //     l.lineWidth = 1
    //     scene.add(l)
    //   }
    // },
    // //跳转到拓扑图列表页面
    // toMapList() {
    //   this.$router.push({path:'/hostMap'});
    // },
    // //计算画布尺寸
    // computedSize(type) {
    //   if(this.mapName === '未选择'){
    //     return 0
    //   }else {
    //     return type === 1?parseInt(this.map.width):parseInt(this.map.height)
    //   }
    // }
  }
};
</script>

<style scoped>
.main {
  height: 88vh;
  margin-top: 60px;
  padding: 10px;
}

.clearfix:before,
.clearfix:after {
  display: table;
}
.clearfix:after {
  clear: both;
}
.clearfix {
  font-weight: bold;
}
.mapCanvas-content {
  text-align: center;
  background-image: linear-gradient(
      90deg,
      rgba(50, 0, 0, 0.1) 2%,
      rgba(0, 0, 0, 0) 2%
    ),
    linear-gradient(360deg, rgba(50, 0, 0, 0.1) 2%, rgba(0, 0, 0, 0) 2%);
  background-size: 50px 50px;
  background-repeat: repeat;
  background-position: center center;
  border: 1px solid #444;
}
.content {
  margin-top: 0;
  overflow-x: hidden;
  overflow-y: hidden;
}
</style>
